package com.xh.bussiness.tiku.controller;

import com.xh.bussiness.exam.service.IUserErrorQuestionService;
import com.xh.bussiness.jingyou.service.IJYBaseDataService;
import com.xh.bussiness.system.model.Dictionary;
import com.xh.bussiness.tiku.bean.dto.KnowledgeDto;
import com.xh.bussiness.tiku.bean.request.KnowledgeRequest;
import com.xh.bussiness.tiku.bean.request.SaveKnowledgeRequest;
import com.xh.bussiness.tiku.model.Knowledge;
import com.xh.bussiness.tiku.service.IKnowledgeService;
import com.xh.core.bean.AjaxResult;
import com.xh.core.bean.XhPage;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.controller.BaseController;
import com.xh.core.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author Pitt zhang
 * @since 2019/4/8
 */
@Api(tags = "知识点接口")
@RestController
@RequestMapping("/tiku/knowledge")
public class KnowledgeController extends BaseController {

    @Autowired
    private IKnowledgeService knowledgeService;
    @Autowired
    private IJYBaseDataService baseDataService;
    @Autowired
    private IUserErrorQuestionService userErrorQuestionService;

    /**
     * 分页查询
     */
    @ApiOperation(value = "知识点分页查询", notes = "知识点分页查询")
    @PostMapping("/queryPage")
    public XhPage queryPage(XhPage page, KnowledgeRequest request) {
        return knowledgeService.queryKnowledgePage(page, request);
    }



    /**
     * 数据查询
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "知识点查询", notes = "知识点查询")
    @PostMapping("/queryAll")
    public AjaxResult queryAll(KnowledgeRequest request) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", knowledgeService.queryKnowledge(request));
    }


    /**
     * 新增和保存
     *
     * @param knowledgeDto 实体对象
     * @return
     */
    @ApiOperation(value = "知识点保存", notes = "知识点保存")
    @PostMapping(value = "/saveOrUpdate")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveOrUpdate(@Validated SaveKnowledgeRequest request) {
        if (StringUtils.isEmpty(request.getId())) {
            knowledgeService.addKnowledge(request);
        } else {
            Knowledge knowledge = knowledgeService.getById(request.getId());
            if (knowledge == null) {
                return new AjaxResult(AjaxResultConstant.Result.ERROR, "知识点不存在");
            }
            knowledge.setName(request.getKnowledgeName());
            knowledgeService.update(knowledge);
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 批量插入知识点
     * @author 赵文博
     * @date 2021/5/20 19:29
     * @param requests
     * @return com.xh.core.bean.AjaxResult
     **/
    @PostMapping("/batchInsertKnowledge")
    public AjaxResult batchInsertKnowledge(@RequestBody List<KnowledgeRequest> requests){
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,knowledgeService.batchInsertKnowledge(requests));
    }

    /**
     * 删除操作
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "知识点删除", notes = "知识点删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "知识点id", required = true, dataType = "String"),
    })
    @PostMapping("/deleteById")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deleteById(String id) {
        knowledgeService.delete(id);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 批量删除操作
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "知识点批量删除", notes = "知识点批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "知识点id集合", required = true, dataType = "String[]"),
    })
    @PostMapping("/batchDelete")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult batchDelete(@RequestBody String[] ids) {
        knowledgeService.batchDelete(ids);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }
    /**
     * 知识点查询树形结构
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "知识点查询树形结构", notes = "知识点查询树形结构")
    @PostMapping("/queryTree")
    public AjaxResult queryTree(KnowledgeRequest request) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", knowledgeService.queryTree(request));
    }

    @ApiOperation(value = "从菁优网拉取考点初始化本地数据库")
    @PostMapping("/initKnowledge")
    public AjaxResult initKnowledge() throws Exception {

        List<Dictionary> data = baseDataService.querySubject();
        List<Knowledge> all = new ArrayList<Knowledge>();
        data.forEach(dic -> {
            try {
                List<Knowledge> points = baseDataService.queryKnowledge(dic.getCode());
                all.addAll(points);
            } catch (Exception e) {
                e.printStackTrace();
                all.clear();
            }
        });
        if (all.isEmpty()) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "失败了");
        }
        // 清空本地库
        knowledgeService.truncateTable();
        // 插入本地库
        knowledgeService.batchInsert(all);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "成功了");
    }

    /**
     * 节点移动
     * @param knowledgeId 章节id
     * @param moveType -1：下移；1：上移
     * @return
     */
    @RequestMapping("/moveUpOrDownKnowledge")
    public AjaxResult moveUpOrDownBookChapter(String knowledgeId, Integer moveType) {
        return new AjaxResult(knowledgeService.moveUpOrDownBookKnowledge(knowledgeId, moveType));
    }

    /**
     * 拖曳移动
     * @author 赵文博
     * @date 2021/4/13 16:43
     * @param requests
     * @return com.xh.core.bean.AjaxResult
     **/
    @RequestMapping("/drag")
    public AjaxResult drag(@RequestBody List<KnowledgeRequest> requests) {
        if(CollectionUtils.isEmpty(requests)){
            return new AjaxResult(AjaxResultConstant.Result.ERROR,"参数错误！");
        }
        knowledgeService.moveUpOrDownBookKnowledge(requests);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 知识点查询树形结构
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "查询有错题的知识点")
    @PostMapping("/queryErrorQuestionKnowledge")
    public AjaxResult queryErrorQuestionKnowledge(@RequestBody KnowledgeRequest request) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", userErrorQuestionService.queryStudentErrorQuesKnowledge(request.getStudentId(), request.getSubjectId(), request.getGradeRange()));
    }
}
